const fs = require('fs/promises');
const path = require('path');
const sharp = require('sharp');



function convertToWebP(inputDir, outputDir, callback) {
    let convertedCount = 0;
    let processed = 0;
    let hasCalledBack = false;  // 新增标志位防止多次回调

    fs.mkdir(outputDir, { recursive: true }, function(err) {
        if (err) return callback(err);
        
        fs.readdir(inputDir, function(err, files) {
            if (err) return callback(err);
            
            const total = files.filter(file => 
                /\.(jpg|jpeg|png|gif|bmp)$/i.test(file)
            ).length;
            
            if (total === 0) return callback(null, { converted: 0 });
            
            files.forEach(function(file) {
                const inputPath = path.join(inputDir, file);
                const outputPath = path.join(outputDir, `${path.parse(file).name}.webp`);

                if (/\.(jpg|jpeg|png|gif|bmp)$/i.test(file)) {
                    sharp(inputPath)
                        .webp({ quality: 90, lossless: false, alphaQuality: 80, effort: 6 })
                        .toFile(outputPath, function (err) {
                            processed++;
                            if (!err) convertedCount++;

                            if (processed === total && !hasCalledBack) {
                                hasCalledBack = true;  // 设置标志位
                                callback(null, { converted: processed });
                            }
                        });
                } else {
                    processed++;
                    if (processed === total && !hasCalledBack) {
                        hasCalledBack = true;  // 设置标志位
                        callback(null, { converted: processed });
                    }
                }
            });
        });
    });
}
module.exports = {
    convertToWebP
};